<?php

class AuthController extends Zend_Controller_Action {

	public function indexAction() {
		return $this->_helper->redirector('login');
	}

	/**
	 *  Login/logout Formular
	 */
	public function loginAction() {
		$auth = Zend_Auth::getInstance();
		$db = $this->_getParam('db');

		$request = $this->getRequest();
		$loginForm = new Application_Form_Auth_Login();

		if ($this->getRequest()->isPost()) {

			if ($this->getRequest()->getParam("logout")) {
				Zend_Auth::getInstance()->clearIdentity();
			} else {

				if ($loginForm->isValid($request->getPost())) {

					$adapter = new Zend_Auth_Adapter_DbTable($db, 'user', 'username', 'password', '?');
					$adapter->setIdentity($loginForm->getValue('username'))->setCredential($loginForm->getValue('password'));
					$auth = Zend_Auth::getInstance();
					$result = $auth->authenticate($adapter);

					if ($result->isValid()) {
						$id = $adapter->getResultRowObject()->id;
						$auth->getStorage()->write($id);
						$auth->getStorage()->write(array("userId", $id));
						$this->_helper->FlashMessenger('Erfolgreich angemeldet');
						return $this->_helper->redirector->gotoUrl('user/list');
					}
					else {
						// todo redirect auf sich selbst wegen flash-Msg "self" funktion?
						$this->_helper->FlashMessenger('user/passwort falsch');
						return $this->_helper->redirector('login');
					}

				}
			}
		}

		if ($this->_getParam('logout') == 'yes') {
			Zend_Auth::getInstance()->clearIdentity();
			$rf = substr($_SERVER['HTTP_REFERER'], 7);
			$rf = substr($rf, strpos($rf, '/') + 1);
			return $this->_helper->redirector->gotoUrl($rf);
		}

		$this->view->form = $loginForm;
	}

}
